import axios from 'axios'
import Vue from 'vue'
// import router from '../router'
let that = new Vue()

const baseURL = location.protocol + '//' + location.host
const http = axios.create({
  baseURL,
  withCredentials: true,
  timeout: 60000,
  isRetryRequest: false,
  headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})
let pending = []
export const removePending = (config) => {
  for (let i in pending) {
    // 全部取消
    if (!config) {
      pending[i].cancel()
      pending.splice(i, 1)
    } else if (pending[i].url === config.url + config.method) { // 取消当前请求的重复请求
      pending[i].cancel()
      pending.splice(i, 1)
    }
  }
}
// 请求拦截器
http.interceptors.request.use(config => {
  removePending(config)
  config.cancelToken = new axios.CancelToken(cancel => {
    pending.push({
      url: config.url + config.method,
      cancel
    })
  })
  return config
}, error => {
  Promise.reject(error)
})
// 返回拦截器
http.interceptors.response.use(res => {
  removePending(res.config)
  // 异常
  if (res.data.status === false) {
    // 返回登录页
    // if(res.data.code === 401){
    //     router.replace('/')
    // }
    res.data.message && that.$message.error(`${res.data.message}`)
    return Promise.reject(res.data.message)
  } else { // 成功
    res.data.message && that.$message.success(`${res.data.message}`)
    return res.data
  }
}, error => {
  error.response && that.$message.error(`${error.response.data.message}`)
  return Promise.reject(error.response)
})
// 统一请求
export function request ({ url, method, data, params }) {
  return http({
    url,
    data,
    params,
    method
  })
}
